package com.lingxu.base.system.manage.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.exception.BussException;
import com.lingxu.base.system.manage.entity.SortInfo;
import com.lingxu.base.system.manage.entity.SysDepart;
import com.lingxu.base.system.manage.mapper.SysDepartMapper;
import com.lingxu.base.system.manage.model.SysDepartTree;
import com.lingxu.base.system.manage.model.SysDepartUserTree;
import com.lingxu.base.system.manage.service.ISysDepartService;
import com.lingxu.base.system.orgManage.vo.ParentTree;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 部门信息
 * @Author: LingXu
 * @Date:   2021-01-04
 * @Version: V1.0.1
 */
@Service
public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart> implements ISysDepartService {

     @Resource
     private SysDepartMapper sysDepartMapper;


     @Override
     public IPage<SysDepart> queryPageList(Page<SysDepart> page, SysDepart sysDepart) {
          return sysDepartMapper.queryList(page,sysDepart);
     }

     @Override
     public void addOne(SysDepart sysDepart) {
          sysDepart.setCreatetime(new Date());
          sysDepart.setIsdel("0");
          sysDepartMapper.insert(sysDepart);
     }


@Override
public Result findDepartTreeByLogin() {
     List<ParentTree> manageTree = sysDepartMapper.findDepartTreeByLogin();
     return Result.ok(buildZzTreeList(manageTree, "mh:1"), "查询成功");
}

     //唯一性部门名称校验
     @Override
     public int findOne(String ename) {
          return sysDepartMapper.findOne(ename);
     }


     @Override
     public Result getSysDepartTree(String pid) {
          List<ParentTree> manageTree = sysDepartMapper.findDepartTreeByPid(pid);
          if(manageTree.size() > 0){
               String ids = manageTree.get(0).getPid();
               return Result.ok(buildTreeList(manageTree,ids),"查询成功");
          }
          return Result.ok("查询成功");
     }

     //pid为空默认看所有层级
     @Override
     public Result findDepartTreeByPidAndEarlyWarn(String pid) {
          List<ParentTree> manageTree = sysDepartMapper.findDepartTreeByPidAndEarlyWarn(pid);
          if(manageTree.size() > 0){
               String ids = manageTree.get(0).getPid();
               return Result.ok(buildTreeList(manageTree,ids),"查询成功");
          }
          return Result.ok("查询成功");
     }
     private static List<ParentTree> buildTreeList(List<ParentTree> treeList,String ids){
          //获取parentId的根节点
          List<ParentTree> areaTrees = treeList.stream().filter(item -> item.getPid().equals(ids)).collect(Collectors.toList());
          //根据parentId进行分组
          Map<String,List<ParentTree>> map = treeList.stream().collect(Collectors.groupingBy(ParentTree::getPid));
          recursionFnTree(areaTrees,map);
          return areaTrees;
     }

     private static void recursionFnTree(List<ParentTree> areaTrees,Map<String,List<ParentTree>> map){
          for(ParentTree areaTree : areaTrees){
               List<ParentTree> childList = map.get(areaTree.getId());
               areaTree.setChildTreeList(childList);
               if (null != childList && 0 < childList.size()){
                    recursionFnTree(childList,map);
               }else {
                    areaTree.setChildTreeList(new ArrayList<>());
               }
          }
     }


     private static List<ParentTree> buildZzTreeList(List<ParentTree> treeList, String rootPid) {
          List<ParentTree> sortedTree = new ArrayList<>(treeList);
          Map<String, List<ParentTree>> map = sortedTree.stream()
                  .collect(Collectors.groupingBy(
                          ParentTree::getPid,
                          LinkedHashMap::new,
                          Collectors.toList()
                  ));

          List<ParentTree> rootNodes = sortedTree.stream()
                  .filter(item -> item.getPid().equals(rootPid))
                  .collect(Collectors.toList());

          recursionBuildZzTree(rootNodes, map);

          return rootNodes;
     }

     private static void recursionBuildZzTree(List<ParentTree> nodes, Map<String, List<ParentTree>> map) {
          for (ParentTree node : nodes) {
               // 1. 获取当前节点的所有子节点
               List<ParentTree> children = map.getOrDefault(node.getId(), new ArrayList<>());

               // 2. 过滤子节点：排除符合条件的部门
               List<ParentTree> filteredChildren = children.stream()
                       .filter(child -> {
                            boolean isExcludeLevel2 = child.getLevel() == 2
                                    && ("mh:45702".equals(child.getId()) || "mh:45701".equals(child.getId()));
                            boolean isExcludeLevel3 = child.getLevel() == 3
                                    && ("mh:49740".equals(child.getId()) || "mh:46980".equals(child.getId()));
                            return !isExcludeLevel2 && !isExcludeLevel3;
                       })
                       .collect(Collectors.toList());

               filteredChildren.sort(Comparator.comparingInt((ParentTree child) ->
                               "厅级领导".equals(child.getName()) ? 0 : 1
                       ).thenComparingInt((ParentTree child) -> {
                            String sortnum = child.getSortnum();
                            if (sortnum == null || sortnum.trim().isEmpty()) {
                                 return 1;
                            } else {
                                 return 0;
                            }
                       }).thenComparing((ParentTree child) -> {
                            String sortnum = child.getSortnum();
                            if (sortnum == null || sortnum.trim().isEmpty()) {
                                 return Integer.MAX_VALUE;
                            }
                            try {
                                 return Integer.parseInt(sortnum.trim());
                            } catch (NumberFormatException e) {
                                 return Integer.MAX_VALUE;
                            }
                       })
               );

               node.setChildTreeList(filteredChildren);

               if (!filteredChildren.isEmpty()) {
                    recursionBuildZzTree(filteredChildren, map);
               }
          }
     }

     @Override
     public Result getSysDepartUserTree() {
          Result result = new Result();
          List<SysDepartUserTree> sysDepartUserTreeold = sysDepartMapper.getSysDepartUserTreeAll();
          List<SysDepartUserTree> sysDepartUserTrees = buildDepartUserTreeList(sysDepartUserTreeold);
          result.setCode(200);
          result.setSuccess(true);
          result.setResult(sysDepartUserTrees);
          return result;
     }

     @Override
     public boolean changeDeptsSortNew(SortInfo param) {
          SysDepart sysDepart = sysDepartMapper.selectById(param.getId());
          String pid = sysDepart.getPid();
          String PsortNum = "0";
          if(StringUtils.isNotBlank(pid)){
               SysDepart PsysDepart = sysDepartMapper.selectById(pid);
               if(PsysDepart!=null && StringUtils.isNotBlank(PsysDepart.getSortnum())){
                    PsortNum=PsysDepart.getSortnum();
               }
          }

          synchronized ("dept_sort_" + param.getId()) {
               List<SysDepart> sysDepartList = sysDepartMapper.getDepsByDeptPid(pid);
               int currentIdx = -1;
               for (int i = 0; i < sysDepartList.size(); i++) {
                    SysDepart p = sysDepartList.get(i);
                    BigInteger PsortNumnew = BigInteger.valueOf(Long.parseLong(PsortNum));
                    String newSortNum = String.valueOf(PsortNumnew.multiply(BigInteger.valueOf(100)).add(BigInteger.valueOf(i+1)));
                    p.setSortnum(newSortNum);
                    if (org.apache.commons.lang3.StringUtils.equals(p.getId(), param.getId())) {
                         currentIdx = i;
                    }
               }
               if (currentIdx != -1) {
                    if (param.getUp()) {
                         if (currentIdx > 0) {
                              SysDepart a = sysDepartList.get(currentIdx);
                              SysDepart b = sysDepartList.get(currentIdx - 1);
                              changeSort(a, b);
                         }
                    } else {
                         if (currentIdx < sysDepartList.size() - 1) {
                              SysDepart a = sysDepartList.get(currentIdx);
                              SysDepart b = sysDepartList.get(currentIdx + 1);
                              changeSort(a, b);
                         }
                    }
                    for(SysDepart depart:sysDepartList){
                         sysDepartMapper.updateSortById(depart);
                    }
//                    sysDepartMapper.updateBatchSortById(sysDepartList);
               } else {
                    throw new BussException("数据存在错误！");
               }
          }
          return true;
     }

     @Override
     public String getCityNameByRgion(String region) {
          return sysDepartMapper.getCityNameByRgion(region);
     }

     @Override
     public List<SysDepart> queryDeptsByPid(String id) {
          return sysDepartMapper.getDepsByDeptPid(id);
     }

     @Override
     public String getDictValueByDictNameAndDictCode(String dictname, String dictcode) {
          return sysDepartMapper.getDictValueByDictNameAndDictCode(dictname,dictcode);
     }


     private void changeSort(SysDepart a, SysDepart b) {
          String i = a.getSortnum();
          a.setSortnum(b.getSortnum());
          b.setSortnum(i);
     }

     private static List<SysDepartUserTree> buildDepartUserTreeList(List<SysDepartUserTree> treeList){
          //获取parentId = 0的根节点
          List<SysDepartUserTree> areaTrees = treeList.stream().filter(item -> item.getPid().equals("0")).collect(Collectors.toList());
          //根据parentId进行分组
          Map<String,List<SysDepartUserTree>> map = treeList.stream().collect(Collectors.groupingBy(SysDepartUserTree::getPid));
          recursionDepartUserTree(areaTrees,map);
          return areaTrees;
     }

     private static void recursionDepartUserTree(List<SysDepartUserTree> areaTrees,Map<String,List<SysDepartUserTree>> map){
          for(SysDepartUserTree areaTree : areaTrees){
               List<SysDepartUserTree> childList = map.get(areaTree.getId());
               areaTree.setChildVOS(childList);
               if (null != childList && 0 < childList.size()){
                    recursionDepartUserTree(childList,map);
               }else {
                    areaTree.setChildVOS(new ArrayList<>());
               }
          }
     }

     private static List<SysDepartTree> buildDepartTreeList(List<SysDepartTree> treeList){
          //获取parentId = 0的根节点
          List<SysDepartTree> areaTrees = treeList.stream().filter(item -> item.getPid().equals("0")).collect(Collectors.toList());
          //根据parentId进行分组
          Map<String,List<SysDepartTree>> map = treeList.stream().collect(Collectors.groupingBy(SysDepartTree::getPid));
          recursionDepartTree(areaTrees,map);
          return areaTrees;
     }

     private static void recursionDepartTree(List<SysDepartTree> areaTrees,Map<String,List<SysDepartTree>> map){
          for(SysDepartTree areaTree : areaTrees){
               List<SysDepartTree> childList = map.get(areaTree.getId());
               areaTree.setChildVOS(childList);
               if (null != childList && 0 < childList.size()){
                    recursionDepartTree(childList,map);
               }else {
                    areaTree.setChildVOS(new ArrayList<>());
               }
          }
     }


     @Override
     public List<SysDepart> d() {
          //查询部门表
          Map map = new HashMap();
          return sysDepartMapper.selectByMap(map);
     }
}
